<template>
  <div class="app-container">
    <!-- 查询参数及按钮部分 queryAgencySalaryInfoByAgencyId -->
    <div class="button">
      <div class="filter-container">
           <el-select 
            ref="agencyTable"
            v-model="state"
            clearable
            class="filter-item"
            style="margin-top: 3px; text-align: -webkit-center; "
            placeholder="-------请选择银行-------"
            @selection-change="handleAgencySelectionChange"
            @row-click="handleAgencyRowClick"
            @change="tableSelect"
            
          >
            <el-option
              v-for="item in agencyBankLists"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        <!-- <el-button
          size="small"
          class="filter-item"
          type="primary"
          @click="handleEdit"
        >
          修改
        </el-button> -->
         <el-button
          size="small"
          class="filter-item"
          type="primary"
          @click="handleSort"
        >
          修改
        </el-button>
        <!-- <el-button
          size="small"
          class="filter-item"
          type="primary"
          :loading="saveBtnLoading"
          @click="handleSave"
        >
          保存
        </el-button> -->
        
      </div>
    </div>
    <!-- 表格部分  @selection-change="handleSelectionChange" :row-key="getRowKeys"-->
    <el-table
      ref="singalTable"
      v-loading="listLoading"
      :data="list"
      :stripe="true"
      :height="tableHeight"
      fit
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      @selection-change="handleSalarySelectionChange"
      @row-click="handleSalaryRowClick"
      :row-key="getRowKeys"
      class="editTable"
         
      s
    >
      <template slot="empty">
        <tableEmpty />
      </template>
     
      <el-table-column type="selection" :reserve-selection="true" width="55"  align="center" @click="checkbox(item)" />
      <el-table-column
        type="index" align="center" width="80"  label="序号"
      />
        <el-table-column label="工资项名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.salaryName }}</span>
        </template>
      </el-table-column>
        <el-table-column
        label="导出顺序"
        align="center"
      >
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-input-number
              v-model="row.sort"
              style="width: 100%;"
              controls-position="right"
              :min="1"
              :max="1000"
              :step="1"
              step-strictly
            />
          </div>
          <span v-else>{{ row.sort }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!--分页部分-->
    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

  <!--排序-->
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="银行排序排序"
      :visible.sync="dialogVerifyFormVisible"
      style="padding: 0px"
      width="31%"
    >
      <el-form
        ref="dataForm"
        label-position="right"
        label-width="0px"
      >
        <el-row>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            :loading="saveLoading"
            @click="dialogVerifyFormVisible = false"
          >
            取消
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            :loading="saveLoading"
            @click="handleSave"
          >
            保存
          </el-button>
        </el-row>
        <el-table
          v-loading="ListLoading"
          max-height="400"
          :data="editListData"
          :stripe="true"
          fit
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          class="editTable"
         
        >
         <template slot="empty">
        <tableEmpty />
          </template>
            <el-table-column
              type="index"
              align="center"
              width="80"
              label="序号"
            />
          <!-- 一个填写框   scope.row.personNum 对应实体的值 -->
          <el-table-column fixed="right" label="工资项名称" align="center" width="200">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.salaryName"
                disabled
                style="width:auto"
                maxlength="200"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="导出排序" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.sort"
                 onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"
                style="width:auto"
                maxlength="9"
              />
            </template>
          </el-table-column>

        </el-table>
      </el-form>
    </el-dialog>

   </div>
</template>

<script>
import {
  queryPage,
  submitData,
  deleteBatchData
} from '@/api/salaryConfigManage/salaryProjectMaintenance'
import {
 saveExportBankType,queryPersonTypeSalaryByType
} from '@/api/generateSalaryData/exportBankType'
import { querySalaryBasedataInfo} from '@/api/salaryConfigManage/salaryProjectConnect'
import {getAgencyBank} from '@/api/baseInfo'
import Pagination from '@/components/Pagination'
import tableEmpty from '@/components/table/empty'
import { Column } from 'vxe-table'

export default {
  name: 'SalaryProjectMaintenance',
  components: {
    Pagination,
    tableEmpty
  },
  filters: {
    dictFilter(value, dictType, that) {
      const dict = that.dict[dictType]
      for (const item of dict) {
        if (value === item.value) {
          return item.label
        }
      }
    },
     bankFilter(type, that) {
      const agencyBankLists = that.agencyBankLists
      for (const item in agencyBankLists) {
        if (agencyBankLists[item].code === type) {
          return agencyBankLists[item].name
        }
      }
      return ''
    },
  },
  data() {
    return {
      getRowKeys(row) {
    return row.id;
      },
      agencyBankLists: [], // 银行
      tableHeight: null,
      that: this,
      generateBtnLoading:false,
      dialogVerifyFormVisible: false,
      ListLoading: false,
      saveLoading: false,
      state:'',
      submitIds: [],
      submitList: [],
      selectionData:[],
      editListData: [],
      salarySelectData: [], // 工资表格选中数据
      bankCode:'',
      addItem: {
        id: '',
        salaryName: '',
        baseState: '1',
        isStandard: 0,
        isCompute: 0,
        isCheck:0,//是否校验功能分类
        isClear: 0,
        isAccsalPay: 0,
        isAccsalWithhold: 0,
        isShow:1,
        decimalPlace: '',
        remark: '',
        isOperate: true,
        isNewItem: '',
        sort:''
      },
      list: [],
      total: 0,
      listLoading: true,
      removeBtnLoading: false,
      saveBtnLoading: false,
      listQuery: {
        page: 1,
        limit: 200,
        state:''
      },
      dict: {
        baseState: [
          { label: '启用', value: '1' },
          { label: '停用', value: '0' }
        ],
        yesOrNo: [{ label: '是', value: 1 }, { label: '否', value: 0 }]
      }
    }
  },
  computed: {
    ids() {
      const selection = this.$refs.singalTable.selection
      const arr = []
      selection.forEach(item => {
        if (!item.isNewItem) {
          arr.push(item.id)
        }
      })
      return arr.join(',')
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    }
  },
  created() {
    this.initBaseInfo()
    this.getList()
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },

  methods: {
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 204
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    getList() {
      this.listLoading = true
      querySalaryBasedataInfo()
        .then(response => {
           const agencyName={salaryCode:'agencyName', salaryName:'单位名称',sort:'0'}
            const agencyCode={salaryCode:'agencyCode', salaryName:'单位编码',sort:'0'}
           const name={salaryCode:'personName',salaryName:'姓名',sort:'0'}
           const idenNo={salaryCode:'idenNo',salaryName:'身份证号码',sort:'0'}
           const bankcode={salaryCode:'salaCardNo',salaryName:'银行卡号',sort:'0'}
            response.data.push(agencyName)
             response.data.push(agencyCode)
            response.data.push(name)
            response.data.push(idenNo)
            response.data.push(bankcode)
           this.list=response.data
        
          // this.total = response.data.total+6
          this.listLoading = false
          this.initData()
        })
        .catch(() => {
          this.initData()
        })
    },  
     handleSalaryRowClick(row) {
      //  console.log(row)
        this.$refs.singalTable.toggleRowSelection(row)
    },
     handleSalarySelectionChange(val) {
      //   console.log(1)
      //  console.log(val)
    this.salarySelectData = val;//勾选放在multipleSelection数组中
},
    tableSelect(row) {
      
      if (this.state !=='') {
       this.queryAgencySalaryInfoByAgencyId()
      }
      if(this.state ==''){
        this.$refs.singalTable.clearSelection()
          this.getList()
      }
      return
    },
        handleAgencyRowClick(row) {
      // console.log(2)
      // 如果当前时选中状态，在点击该数据时，取消选中
      if (this.agencySelectData.length > 0) {
        if (row.personTypeId !== this.agencySelectData[0].personTypeId) {
          this.$refs.agencyTable.clearSelection()
          this.$refs.agencyTable.toggleRowSelection(row)
        } else {
          this.$refs.agencyTable.toggleRowSelection(row)
        }
      } else {
        this.$refs.agencyTable.toggleRowSelection(row)
      }
    },
      handleAgencySelectionChange(val) {
    console.log(2)
     
      this.$refs.singalTable.clearSelection()
      const array = []
      // 获取表格选中数据,放到数组中缓存
      const selectionData = this.$refs.agencyTable.selection
        //  console.log(selectionData)
        //  console.log(val)
      for (let i = 0; i < val.length; i++) {
        if (selectionData[0].personTypeId === val[i].personTypeId) {
          array.push(val[i])
        }
      }
      this.agencySelectData = selectionData
      // 获取单位现有的工资项
      if (val.length > 0) {
        this.personTypeCode = selectionData[0].personTypeCode
        this.queryAgencySalaryInfoByAgencyId()
      } else {
        // 当单位表格取消选中时，将工资项表格选中状态清空
        this.$refs.singalTable.clearSelection()
      }
    },
    initData() {
      this.submitIds = []
      this.submitList = []
    },
     initBaseInfo() { 
       getAgencyBank().then(response => {
        this.agencyBankLists = Object.assign({}, response.data)
      })},
    handleAdd() {
      const addItem = { ...this.addItem }
      addItem.isNewItem = Math.random()
        .toString(16)
        .substr(2, 8)
      this.list.unshift(addItem)
      this.submitList.push(addItem)
    },
   
    handleEdit() {
      const selection = this.$refs.singalTable.selection
      if (selection.length == 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      if (!this.submitIds.includes(selection[0].id)) {
        this.$set(selection[0], 'isOperate', true)
        this.submitIds.push(selection[0].id)
        this.submitList.push(selection[0])
      }
    },

    handleRemove() {
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          message: '请选择至少一条数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      for (const select of selection) {
        if (
          select.id === '46F1370C5F2A4D31AD196718A93DC470' ||
          select.id === '3C4B5B347C9F420BB8D4B86572A5F178'
        ) {
          this.$message({
            message: '应发项和实发工资不可删除',
            type: 'warning',
            showClose: true,
            duration: 4000
          })
          return
        }
      }
      this.removeBtnLoading = true
      this.$confirm('确定删除吗？', '提示', {
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除新增的数据
          this.removeNewItem(selection)
          // 删除数据库中的数据
          if (this.ids) {
            deleteBatchData(this.ids)
              .then(() => {
                this.$message({
                  message: '删除成功',
                  type: 'success',
                  showClose: true,
                  duration: 4000
                })
                this.handleFilter()
                this.removeBtnLoading = false
              })
              .catch(() => {
                this.removeBtnLoading = false
              })
          } else {
            this.removeBtnLoading = false
          }
        })
        .catch(() => {
          this.removeBtnLoading = false
        })
    },

    removeNewItem(selection) {
      const newItemArr = []
      selection.forEach(item => {
        if (item.isNewItem) {
          newItemArr.push(item.isNewItem)
        }
      })
      if (newItemArr.length > 0) {
        const list = this.list
        for (let i = 0; i < list.length; i++) {
          if (newItemArr.indexOf(list[i].isNewItem) > -1) {
            list.splice(i--, 1)
          }
        }
        const submitList = this.submitList
        for (let i = 0; i < submitList.length; i++) {
          if (newItemArr.indexOf(submitList[i].isNewItem) > -1) {
            submitList.splice(i--, 1)
          }
        }
      }
     },
     handleSort() {
      const queryPersonInfo = []
      // 获取当前 点击的数据
      const selection = this.$refs.singalTable.selection
            if(this.state===0||this.state===''){
              this.$message({     
                message: '请选择银行后在保存',
                type: 'warning',
                showClose: true,
                duration: 2000
              })
              return
            }
      if (selection.length === 0) {
        // 将请最少选择一条数据返回
        this.$message({
          showClose: true,
          message: '请至少选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      // 获取第一条的数据
      //  console.log(selection)
        selection.forEach(item => {
        const current = {}
        current['salaryId'] = item.id
        current['salaryName'] = item.salaryName
        current['columnName'] = item.salaryCode
        current['sort'] = item.sort
        queryPersonInfo.push(current)
      })
      // 将queryPersonInfo 赋值给 this.editListData
    
      this.editListData = queryPersonInfo
      // 打开页面
      this.dialogVerifyFormVisible = true
    },
     handleSave() {
      this.saveLoading = true
      // 创建一个集合数组
      const expoptList = []
      
      // 获取当前值
      const editListData = this.unique()
   
      // 将当前的存入 map 循环存入 返回给后台
      editListData.forEach(item => {      
        // 创建一个map
        const current = {}
        current['salaryId'] = item.salaryId
        current['salaryName'] = item.salaryName
        current['columnName'] = item.columnName
        current['bankType'] = this.state
        current['sort'] = item.sort  
        expoptList.push(current)
      })
      // 接口 插入或者保存
     
      saveExportBankType(expoptList).then((response) => {
        this.dialogEditFormVisible = false
        this.$message({
          showClose: true,
          message: '保存成功',
          type: 'success',
          duration: 4000
        })
         this.handleFilter()
        this.saveBtnLoading = false
        this.saveLoading = false
        this.dialogVerifyFormVisible = false
        // 保存后调用刷新方法
        this.handleFilter()
      }).catch(() => {
         this.saveBtnLoading = false
        this.saveLoading = false
      })
    },// 人员排序按钮
    // 获取当前值
    unique() {
      const editListData = this.editListData
      return editListData
    },

        queryAgencySalaryInfoByAgencyId() {
            const tmp = {
        bankCode:this.state
      }
         
      queryPersonTypeSalaryByType(tmp).then(respose => {
        // console.log(respose)
        // 如果有挂接，将已挂接的工资项选中
        // if(respose.data.length==0){
        //       this.getList()
        // }
        if (respose.data.length > 0) {
          this.$refs.singalTable.clearSelection()
           this.list.forEach(row => {
          respose.data.forEach(val => {
             
              if (val.salaryName == row.salaryName) {
                row.sort=val.sort
               this.$refs.singalTable.toggleRowSelection(row, true)
                return
              }else{
                 val.checked = false
              }
            })
          })
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.app-title {
  margin-bottom: 15px;
  height: 20px;
  border-bottom: 1px solid #dcdfe6;
}

.filter-item{
  margin-top: -3px;
  margin-left:7px;
  margin-right: 6px;
}
.button {
  float: right;
}

/** 文本框高度 **/
::v-deep .el-input {
  width: auto !important;
}
</style>
